<!--
 * @Author: Wushiqi
 * @Descripttion: 登录页面
 * @Date: 2020-07-31 15:46:41
 * @LastEditor: Wushiqi
 * @LastEditTime: 2021-04-19 16:18:15
-->
<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on" label-position="left">
      <div class="title-container"><h3 class="title">用户登录</h3></div>
      <el-form-item prop="username">
        <span class="svg-container"><svg-icon icon-class="user" /></span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="请输入用户名"
          name="username"
          type="text"
          tabindex="1"
          autocomplete="on"
          @input="e => loginForm.username = validForbid (e)"
          @keyup.enter.native="handleLogin"
        />
      </el-form-item>

      <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
        <el-form-item prop="password">
          <span class="svg-container"><svg-icon icon-class="password" /></span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            placeholder="请输入密码"
            name="password"
            tabindex="2"
            autocomplete="on"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd"><svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" /></span>
        </el-form-item>
      </el-tooltip>
      <el-form-item v-if="showCode" prop="verifyCode" class="verify-code-item">
        <el-input ref="verifyCodeInput" v-model="loginForm.verifyCode" placeholder="请输入验证码" clearable @clear="verifyCodeClear" @keyup.enter.native="handleLogin" />
        <div>
          <span v-if="codeLoading"><i class="el-icon-loading" />加载中</span>
          <img v-else :src="codeImgUrl" alt="" title="点击更换" @click="getVerifyCode">
        </div>
      </el-form-item>
      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native="handleLogin">登录</el-button>
    </el-form>
  </div>
</template>

<script>
import { validUsername } from '@/utils/validate'
import { encrypt } from '@/utils/aes'
import '@/common/common'
import publicAPI from '@/utils/api/public/public'
import axios from 'axios'
import common from '@/common/common'

export default {
  name: 'Login',
  data() {
    // 用户名只能是字母，这里只是验证输入的是否规范,并不是提交时候的验证
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('* 请输入正确的用户名'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('* 密码不能少于6位'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        'username': '',
        'password': '',
        verifyCode: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        verifyCode: [{ required: true, message: '*请输入验证码' }]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      redirect: undefined,
      otherQuery: {},
      codeImgUrl: '',
      showCode: false,
      errorNum: 0,
      codeLoading: false
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    },
    errorNum() {
      if (this.errorNum > 2) {
        this.showCode = true
        this.getVerifyCode()
      }
    }
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    } else if (this.loginForm.verifyCode === '' && this.$refs.verifyCodeInput) {
      this.$refs.verifyCodeInput.focus()
    }
    if (localStorage.errorNum > 2) {
      this.showCode = true
      this.getVerifyCode()
    }
  },
  methods: {
    checkCapslock({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if (shiftKey && (key >= 'a' && key <= 'z') || !shiftKey && (key >= 'A' && key <= 'Z')) {
          this.capsTooltip = true
        } else {
          this.capsTooltip = false
        }
      }
      if (key === 'CapsLock' && this.capsTooltip === true) {
        this.capsTooltip = false
      }
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    // 登录
    async handleLogin() {
      const username = encrypt(this.loginForm.username)
      const password = encrypt(this.loginForm.password)
      this.$refs.loginForm.validate(async(valid) => {
        if (valid) {
          this.loading = true
          await publicAPI.loginAPI({ username, password, verifyCode: this.loginForm.verifyCode }).then(response => {
            const res = response.data
            if (res.flag === 'success') {
              sessionStorage.setItem('_csrf', res.data._csrf)
              sessionStorage.setItem('newLogin', 'true')
              this.$successMsg('恭喜你，登录成功！')
              localStorage.setItem('errorNum', 0) // 登录错误的次数
              this.$store.dispatch('user/updateInitPwd', res.data.initPwd)
              this.$router.push({ path: '/' })
            } else {
              this.$errorMsg(res.data)
              this.$router.push({ path: '/login' })
              this.loading = false
              if (res.errcode === 4001101) {
                if (!localStorage.errorNum || localStorage.errorNum === '0') {
                  localStorage.setItem('errorNum', 1)
                  this.errorNum = localStorage.errorNum
                } else {
                  localStorage.setItem('errorNum', Number(localStorage.errorNum) + 1)
                  this.errorNum = localStorage.errorNum
                }
              } else if (res.errcode === 4001110 || Number(localStorage.errorNum) > 2) {
                this.getVerifyCode()
                this.showCode = true
              }
            }
          }).catch(error => {
            this.$errorMsg('' + error)
            this.loading = false
          })
        } else {
          // 表单验证不成功（填写不正确）
          console.log('error submit!!')
          return false
        }
      })
    },
    // 统计登录错误的次数
    getErrorNumber: function() {
      if (!localStorage.errorNum) {
        localStorage.setItem('errorNum', 1)
      } else {
        localStorage.setItem('errorNum', localStorage.errorNum + 1)
      }
    },
    // 获取验证码
    getVerifyCode: function() {
      this.codeLoading = true
      axios({
        method: 'GET',
        url: '/login/verifyCode',
        responseType: 'blob'
      }).then(response => {
        this.codeImgUrl = common.getObjectURL(response.data)
        this.codeLoading = false
      })
    },
    // 验证码清空后自动选中输入框
    verifyCodeClear: function() {
      this.$refs.verifyCodeInput.focus()
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
$bg:#283443;
$light_gray:#fff;
$cursor: #fff;
@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}
/* reset element-ui css */
.login-container {
  .el-form-item__error {
    margin-top: 2px;
  }
  .el-input {
    display: inline-block;
    height: 43px;
    width: 85%;
    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 43px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }
  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background-color: rgb(40,52,67);
    border-radius: 5px;
    color: #454545;
  }
  .verify-code-item {
    text-align: right;
    .el-input {
      input {
        line-height: 43px;
        height: 43px;
      }
    }
  }
}
</style>

<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;
$form_bg: #303d50;
.login-container {
  height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  padding: 0;
  margin: 0;
  .login-form {
    background-color: rgba(225, 234, 255, 0.062);
    width: 500px;
    max-width: 100%;
    padding: 20px 70px;
    margin: 0 auto; //  使表单水平居中
    overflow: hidden;
    height: 350px;
    border: 1px solid  rgba(255, 255, 255, 0.1);
    border-radius: 10px;
    box-shadow: 10px 10px 5px #333333c5;
    // 使表单垂直居中
    position: relative;
    top: 50%;
    margin-top: -175px;
  }
  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }
  .title-container {
    position: relative;
    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 12px auto 25px auto;
      text-align: center;
      font-weight: bold;
    }
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  .verify-code-item {
    border: 0;
    background-color: transparent;
    div {
      height: 100%;
      display: inline-block;
      vertical-align: middle;
      img,
      span {
        display: inline-block;
        width: 110px;
        height: 45px;
        text-align: center;
        color: $light_gray;
        line-height: 45px;
        vertical-align: middle;
        cursor: pointer;
      }
    }
    .el-input {
      width: 227px;
      border: 1px solid rgba(255, 255, 255, 0.1);
      color: $dark_gray;
      background-color: rgb(40,52,67);
      border-radius: 5px;
      height: 43px;
      vertical-align: middle;
      line-height: 43px;
      margin-right: 16px;
    }
  }
}
</style>
